/**
 * Project Name:HomeActivity
 * Date:2016-3-3上午10:22:42
 * Copyright (c) 2016, askzhao All Rights Reserved.
 *
 */
package com.kkd.kkdapp.adapter;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.activity.AccountEverydayActivity;
import com.kkd.kkdapp.activity.ForTenderActivity;
import com.kkd.kkdapp.activity.ExperienceParticularsActivity;
import com.kkd.kkdapp.activity.LoginActivity;
import com.kkd.kkdapp.activity.RegularParticularsActivity;
import com.kkd.kkdapp.activity.TenderAffirmActivity;
import com.kkd.kkdapp.activity.AccountEverydayActivity.TimerHandler;
import com.kkd.kkdapp.http.entity.HomeTender;
import com.kkd.kkdapp.http.entity.MyExperienceGoldItem;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;
import com.kkd.kkdapp.view.shapeimageview.PorterShapeImageView;
import com.umeng.message.PushAgent;
import com.umeng.message.local.UmengLocalNotification;
import com.umeng.message.local.UmengNotificationBuilder;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * ClassName: RegularAdapter <br/>
 * date: 2016-3-3 上午10:22:42 <br/>
 * 
 * @author askzhao
 * @version
 */
public class RegularAdapterForMyExperienceGold extends BaseAdapter {
	private static List<MyExperienceGoldItem> datalist;
	private Context mContext;
	private double balance;
	private Toast mToast;

	public RegularAdapterForMyExperienceGold(Context context,
			List<MyExperienceGoldItem> data) {
		mContext = context;
		datalist = data;
	}

	@Override
	public int getCount() {
		return datalist.size();
	}

	@Override
	public Object getItem(int position) {

		return datalist.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		return getBidView(position, convertView, parent);
	}

	/**
	 * getBidView:(这里用一句话描述这个方法的作用). <br/>
	 * 
	 * @author askzhao
	 * @param position
	 * @param convertView
	 * @param parent
	 */
	private View getBidView(final int position, View convertView,
			ViewGroup parent) {
		ViewHolder mViewHolder;

		if (convertView == null
				|| !(convertView.getTag() instanceof ViewHolder)) {
			convertView = LayoutInflater.from(mContext).inflate(
					R.layout.inthebidding_list_item_tiyan, null);
			mViewHolder = new ViewHolder();
			// 上部点击进入标的详情界面
			mViewHolder.top = (RelativeLayout) convertView
					.findViewById(R.id.top);
			// 标题
			mViewHolder.refund_name = (TextView) convertView
					.findViewById(R.id.refund_name);
			// 标的类型
			mViewHolder.type_bg = (PorterShapeImageView) convertView
					.findViewById(R.id.type_bg);
			mViewHolder.type_tv = (TextView) convertView
					.findViewById(R.id.type_tv);
			// 年利率
			mViewHolder.interest_tv = (TextView) convertView
					.findViewById(R.id.interest_tv);
			// 加息
			mViewHolder.rise_tv1 = (TextView) convertView
					.findViewById(R.id.rise_tv1);
			// 理财期限
			mViewHolder.deadline_tv = (TextView) convertView
					.findViewById(R.id.deadline_tv);
			// 理财期限单位
			mViewHolder.deadline_company_tv = (TextView) convertView
					.findViewById(R.id.deadline_company_tv);
			// 可购买金额
			mViewHolder.can_buy = (TextView) convertView
					.findViewById(R.id.can_buy);
			// 进度条
			mViewHolder.progressbar = (ProgressBar) convertView
					.findViewById(R.id.progressbar);
			// 进度条百分比
			mViewHolder.speed_of_progress = (TextView) convertView
					.findViewById(R.id.speed_of_progress);
			// 按钮
			mViewHolder.bid = (TextView) convertView.findViewById(R.id.bid);
			convertView.setTag(mViewHolder);
		} else {
			mViewHolder = (ViewHolder) convertView.getTag();
		}
		/*************** 标题 *****************/
		mViewHolder.refund_name.setTag(position);
		mViewHolder.refund_name.setText(datalist.get(position).getBidTitle());
		/*************** 标的类型 **************/
		mViewHolder.type_bg.setTag(position);
		mViewHolder.type_tv.setTag(position);
		mViewHolder.type_tv.setText(datalist.get(position).getBidTypeName());
		mViewHolder.type_tv.setTextColor(Color.parseColor("#FFA757"));
		mViewHolder.type_bg.setImageColor(Color.parseColor("#FFA757"));
		/**************** 年利率 **************/
		mViewHolder.interest_tv.setTag(position);
		mViewHolder.rise_tv1.setTag(position);
		String interestDisplay = datalist.get(position).getInterestDisplay();
		mViewHolder.interest_tv.setText(interestDisplay + "%");
		if (interestDisplay.indexOf("+") == -1) {
			mViewHolder.interest_tv.setText(interestDisplay + "%");
			mViewHolder.rise_tv1.setText("");
			mViewHolder.rise_tv1.setBackgroundResource(0);
		} else {
			String[] idp = interestDisplay.split("\\+");
			mViewHolder.interest_tv.setText(idp[0] + "%");
			mViewHolder.rise_tv1.setText("+" + idp[1] + "%");
			mViewHolder.rise_tv1
					.setBackgroundResource(R.drawable.increase_interest_img);
		}
		// if (mList.get(position).getInterestDisplay().length() > 7) {
		// mViewHolder.interest_tv.setTextSize(18);
		// mViewHolder.interest_tv.setText(mList.get(position)
		// .getInterestDisplay() + "%");
		// } else {
		// mViewHolder.interest_tv.setTextSize(26);
		// mViewHolder.interest_tv.setText(mList.get(position)
		// .getInterestDisplay() + "%");
		// }
		/*************** 标的期限 *****************/
		mViewHolder.deadline_tv.setTag(position);
		mViewHolder.deadline_tv.setText(datalist.get(position)
				.getBidPeriodValue() + "");
		/*************** 标的期限单位 ******************/
		String bidPeriodType = datalist.get(position).getBidPeriodType();
		if ("月".equals(bidPeriodType)) {
			mViewHolder.deadline_company_tv.setText("个" + bidPeriodType);
		} else if ("天".equals(bidPeriodType)) {
			mViewHolder.deadline_company_tv.setText(bidPeriodType);
		}
		/*************** 可购买金额 **************/
		mViewHolder.can_buy.setText("可购买金额   "
				+ SystemUtils.numberWithDelimiter(datalist.get(position)
						.getBidFreeAmount() / 100) + "元");
		/****************** 标的进度 ****************/
		int bidAmout = (int) (datalist.get(position).getBidAmount() / 100);
		LogUtil.e("bidAmout", "" + bidAmout);
		double bidFreeAmount = datalist.get(position).getBidFreeAmount() * 0.01;
		int interest = (int) Math.ceil((1 - bidFreeAmount / bidAmout) * 100);
		LogUtil.e("interest", "" + interest);
		mViewHolder.progressbar.setProgress(interest);
		/***************** 进度条进度百分比 ***********/
		mViewHolder.speed_of_progress.setText(datalist.get(position)
				.getBidProgress() + "%");
		/***************** 标的状态 *******************/
		mViewHolder.bid.setTag(position);
		mViewHolder.bid.setEnabled(true);
		mViewHolder.bid.setClickable(true);
		final String bidStatus = datalist.get(position).getBidStatus();
		if ("5001".equals(bidStatus)) {
			mViewHolder.bid.setText("新建");
			mViewHolder.bid.setEnabled(false);
			mViewHolder.bid.setClickable(false);
		} else if ("5002".equals(bidStatus)) {
			if (position == 0
					&& datalist.get(position).getBidTypeName().endsWith("快快享福")
					&& datalist.get(position).getCountDown() > 0) {
				mViewHolder.bid.setEnabled(false);
				mViewHolder.bid.setClickable(false);
				if (isRecoding) {
					int time = (int) datalist.get(position).getCountDown();
					int min = time / 60;
					int sec = time % 60;
					String text = String.format("%02d:%02d\n后抢购", min, sec);
					mViewHolder.bid.setText(text);
				} else {
					maxTime = (int) datalist.get(position).getCountDown();
					startCountdown(mViewHolder.bid, datalist.get(position)
							.getCountDown(), position);

				}

			} else {
				mViewHolder.bid.setText("投标");
			}

			mViewHolder.bid.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (isRecoding) {
						if (AppUtil.isConnect(mContext)) {
							if (PreferenceUtils.getInstance()
									.getLogin(mContext) == 0) { // 登陆验证

								if (PreferenceUtils.getInstance().getAutonym(
										mContext) == 1) { // 身份认证

									if (PreferenceUtils.getInstance()
											.getBoundBankCard(mContext) == 1) { // 判定银行卡是否绑定
										gotoTenderActivity(datalist
												.get(position));
									} else {
										getAccountInfo(datalist.get(position));

									}

								} else {
									gotoTrueIDVerifyActivity(datalist
											.get(position));

								}

							} else {

								Intent intent = new Intent(mContext,
										LoginActivity.class);
								mContext.startActivity(intent);

							}
						} else {
							// showToast(R.string.network_anomaly);
							AppUtil.makeToastForCustomer(mContext,
									R.string.network_anomaly);
						}
					}
				}
			});
		} else if ("5003".equals(bidStatus)) {
			mViewHolder.bid.setText("满标");
			mViewHolder.bid.setClickable(false);
		} else if ("5004".equals(bidStatus)) {
			mViewHolder.bid.setText("还款中");
			mViewHolder.bid.setClickable(false);
		} else if ("5005".equals(bidStatus)) {
			mViewHolder.bid.setText("已还清");
			mViewHolder.bid.setEnabled(false);
			mViewHolder.bid.setClickable(false);
		} else if ("5006".equals(bidStatus)) {
			mViewHolder.bid.setText("待发布");
			mViewHolder.bid.setEnabled(false);
			mViewHolder.bid.setClickable(false);
		} else if ("5007".equals(bidStatus)) {
			mViewHolder.bid.setText("处理中");
			mViewHolder.bid.setEnabled(false);
			mViewHolder.bid.setClickable(false);
		} else if ("4011".equals(bidStatus)) {
			mViewHolder.bid.setText("已流标");
			mViewHolder.bid.setEnabled(false);
			mViewHolder.bid.setClickable(false);
		}

		mViewHolder.top.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String bidType = datalist.get(position).getBidType();
				if ("501".equals(bidType)) {
					Intent intent = new Intent(mContext,
							ExperienceParticularsActivity.class);
					intent.putExtra("bidId", datalist.get(position).getBidId());
					intent.putExtra("bidType", datalist.get(position)
							.getBidType());
					mContext.startActivity(intent);
				} else {
					Intent intent = new Intent(mContext,
							RegularParticularsActivity.class);
					intent.putExtra("bidId", datalist.get(position).getBidId());
					intent.putExtra("bidType", datalist.get(position)
							.getBidType());
					mContext.startActivity(intent);
				}
			}
		});
		return convertView;

	}

	public static final int PERIOD = 1000;
	public int maxTime = 0;
	public static final int RECORD_TIMER = 8112;
	public static final int RECORD_DONE = 8113;
	public static final int RECORD_ERROR = 8114;
	private int mRecordTime = 0;
	private boolean isRecoding = false;
	private Timer mTimer = new Timer();
	private TimerTask mTimerTask = null;

	private void startCountdown(TextView bid, long countDown, int position) {
		mRecordTime = 0;
		if (mTimerTask == null) {
			mTimerTask = new RecordTimeTask();
			mTimer.schedule(mTimerTask, 0, PERIOD);
		}
		isRecoding = true;

	}

	public TimerHandler mTimerHandler = new TimerHandler(this);
	protected boolean onStarting = false;

	public static class TimerHandler extends Handler {
		WeakReference<RegularAdapterForMyExperienceGold> reference;

		public TimerHandler(RegularAdapterForMyExperienceGold view) {
			reference = new WeakReference<RegularAdapterForMyExperienceGold>(
					view);
		}

		@Override
		public void dispatchMessage(Message msg) {
			switch (msg.what) {
			case RECORD_TIMER:
				if (reference != null && reference.get() != null) {
					try {
						datalist.get(0).setCountDown(
								datalist.get(0).getCountDown() - 1);
						reference.get().notifyDataSetChanged();
					} catch (Exception e) {
					}

				}
				break;
			case RECORD_DONE:
				if (reference != null && reference.get() != null) {
					try {
						datalist.get(0).setCountDown(0);
						reference.get().notifyDataSetChanged();
					} catch (Exception e) {
					}
				}
				break;
			default:
				break;
			}
		}
	}

	private class RecordTimeTask extends TimerTask {
		@Override
		public void run() {
			if (isRecoding) {
				mRecordTime++;
				if (mRecordTime <= maxTime) {
					Message message = new Message();
					message.what = RECORD_TIMER;
					message.obj = mRecordTime;
					mTimerHandler.sendMessage(message);
				} else {
					Message message = new Message();
					message.what = RECORD_DONE;
					message.arg1 = mRecordTime;
					message.obj = "";
					mTimerHandler.sendMessage(message);
					isRecoding = false;
				}
			}

		}
	}

	public void onDestroy() {
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		if (mTimerTask != null) {
			mTimerTask.cancel();
			mTimerTask = null;
		}
	}

	/**
	 * 
	 * 查询账户余额
	 */
	public void getAccountInfo(final MyExperienceGoldItem tenderData) {

		KkdHttpMagager.getInstance().getAccountInfoManager(
				String.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						try {
							String responseString = responseBody.toString();
							JSONObject data = new JSONObject(responseString);
							balance = data.getDouble("balance");
							if (balance == 0) {
								gotoAddBankActivity(tenderData);

							} else {
								gotoTenderActivity(tenderData);
							}

						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						showToast(desc);
					}
				});
	}

	private class ViewHolder {
		RelativeLayout top;
		TextView refund_name;
		TextView interest_tv;
		TextView deadline_tv;
		ProgressBar progressbar;
		TextView bid;
		PorterShapeImageView type_bg;
		TextView speed_of_progress;
		TextView can_buy;
		TextView type_tv, deadline_company_tv;
		TextView rise_tv1;
	}

	public void showToast(String hintLanguage) {
		if (mToast != null) {
			mToast.cancel();
			mToast = null;
		}
		mToast = Toast.makeText(mContext, hintLanguage, Toast.LENGTH_SHORT);
		mToast.show();
	}

	public void showToast(int hintLanguage) {
		if (mToast != null) {
			mToast.cancel();
			mToast = null;
		}
		mToast = Toast.makeText(mContext, hintLanguage, Toast.LENGTH_SHORT);
		mToast.show();
	}

	public void gotoTenderActivity(MyExperienceGoldItem tenderData) {
		Intent intent = new Intent(mContext, TenderAffirmActivity.class);
		intent.putExtra("bidId", tenderData.getBidId());
		intent.putExtra("bidTitle", tenderData.getBidTitle());
		intent.putExtra("bidPeriod", tenderData.getBidPeriod());
		intent.putExtra("amountMultiple", tenderData.getAmountMultiple());
		intent.putExtra("lowestAmount", tenderData.getLowestAmount());
		intent.putExtra("bidPeriodType", tenderData.getBidPeriodType());
		intent.putExtra("bidInterest", tenderData.getInterestDisplay());
		intent.putExtra("bidFreeAmount", tenderData.getBidFreeAmount());
		intent.putExtra("maxAmount", tenderData.getMaxAmountDisplay());
		intent.putExtra("bidAmount", tenderData.getBidAmount());
		intent.putExtra("totalLixi", tenderData.getTotalLixi());
		intent.putExtra("bidType", tenderData.getBidType());
		intent.putExtra("businessType", "1");// 区分信用标还是抵押标
		intent.putExtra("isNewbie", tenderData.getIsNewbie());
		if ("501".equals(tenderData.getBidType())) {// 为体验标
			//并且没有快快享福特权
			if(PreferenceUtils.getInstance().getKkxfStatus(mContext) == 0){
				AppUtil.makeToastForCustomer(mContext, PreferenceUtils
						.getInstance().getKkxfExt(mContext));
			}else{
				if(tenderData.getCountDown()<=0){
					mContext.startActivity(intent);
				}else{
					registerNotification(tenderData.getCountDown(), tenderData.getBidTitle());
					showToast("将在开标前3分钟通过推送消息通知您");
				}
				
			}
			
		} else {
			mContext.startActivity(intent);
		}
	}

	public void gotoTrueIDVerifyActivity(MyExperienceGoldItem tenderData) {
		Intent intent = new Intent(mContext, ForTenderActivity.class);
		intent.putExtra("enterTypeFlag", 5);
		intent.putExtra("bidId", tenderData.getBidId());
		intent.putExtra("bidTitle", tenderData.getBidTitle());
		intent.putExtra("bidPeriod", tenderData.getBidPeriod());
		intent.putExtra("amountMultiple", tenderData.getAmountMultiple());
		intent.putExtra("lowestAmount", tenderData.getLowestAmount());
		intent.putExtra("bidPeriodType", tenderData.getBidPeriodType());
		intent.putExtra("bidInterest", tenderData.getInterestDisplay());
		intent.putExtra("bidFreeAmount", tenderData.getBidFreeAmount());
		intent.putExtra("maxAmount", tenderData.getMaxAmountDisplay());
		intent.putExtra("bidAmount", tenderData.getBidAmount());
		intent.putExtra("totalLixi", tenderData.getTotalLixi());
		intent.putExtra("businessType", "1");
		intent.putExtra("isNewbie", tenderData.getIsNewbie());
		mContext.startActivity(intent);
	}

	public void gotoAddBankActivity(MyExperienceGoldItem tenderData) {
		Intent intent = new Intent(mContext, ForTenderActivity.class);
		intent.putExtra("enterTypeFlag", 5);
		intent.putExtra("bidType", tenderData.getBidType());
		intent.putExtra("bidId", tenderData.getBidId());
		intent.putExtra("bidTitle", tenderData.getBidTitle());
		intent.putExtra("bidPeriod", tenderData.getBidPeriod());
		intent.putExtra("amountMultiple", tenderData.getAmountMultiple());
		intent.putExtra("lowestAmount", tenderData.getLowestAmount());
		intent.putExtra("bidPeriodType", tenderData.getBidPeriodType());
		intent.putExtra("bidInterest", tenderData.getBidInterest());
		intent.putExtra("bidFreeAmount", tenderData.getBidFreeAmount());
		intent.putExtra("maxAmount", tenderData.getMaxAmountDisplay());
		intent.putExtra("bidInterest", tenderData.getInterestDisplay());
		intent.putExtra("bidAmount", tenderData.getBidAmount());
		intent.putExtra("totalLixi", tenderData.getTotalLixi());
		intent.putExtra("businessType", "1");
		intent.putExtra("isNewbie", tenderData.getIsNewbie());
		mContext.startActivity(intent);
	}
	
	// 注册通知
		public void registerNotification(long coutDown, String title) {

			// 开发者可以自定义本地通知
			UmengLocalNotification localNotification = new UmengLocalNotification();

			// 自定义本地通知相关属性：
			localNotification.setTitle(title + "马上开标啦。"); // 设置通知标题
			localNotification.setContent("赶紧登录快快贷来抢吧。"); // 设置通知内容

			Date nowTime = new Date(System.currentTimeMillis() + coutDown - 1000
					* 60 * 3);
			SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			localNotification.setTicker(title + "马上开标啦，赶紧登录快快贷来抢吧。"); // 设置通知提示
			localNotification.setDateTime(time.format(nowTime)); // 设置通知开始时间
			// localNotification.setLunarDateTime(String dateTime); //设置通知开始的阴历时间
			// localNotification.setSpecialDay(int specialDay); //设置通知节日
			// localNotification.setRepeatingNum(int repeatingNum); //设置通知重复数，默认是1
			// localNotification.setRepeatingInterval(int repeatingInterval);
			// //设置通知重复间隔，默认是1
			// localNotification.setRepeatingUnit(int repeatingUnit); //设置通知重复单位

			// 开发者可以自定义本地通知样式
			UmengNotificationBuilder notificationBuilder = localNotification
					.getNotificationBuilder();

			// 针对通知通用属性的设置:
			// notificationBuilder.setDefaults(int defaults); //设置Defaults
			// notificationBuilder.setFlags(int flags); //设置Flags
			// notificationBuilder.setSmallIconDrawable(""); //设置小图标
			// notificationBuilder.setLargeIconDrawable(String drawable); //设置大图标
			// notificationBuilder.setSoundDrawable(String drawable); //设置声音
			notificationBuilder.setPlayVibrate(true); // 设置振动
			// notificationBuilder.setPlayLights(boolean lights); //设置呼吸灯
			notificationBuilder.setPlaySound(true); // 设置声响
			notificationBuilder.setScreenOn(true); // 设置屏显

			// 针对通知自定义样式的设置：
			// notificationBuilder.setLayoutId(int layoutId); //设置自定义样式Id
			// notificationBuilder.setLayoutTitleId(int layoutTitleId); //设置自定义标题Id
			// notificationBuilder.setLayoutContentId(int layoutContentId);
			// //设置自定义内容Id
			// notificationBuilder.setLayoutIconId(int layoutIconId); //设置自定义小图标Id
			// notificationBuilder.setLayoutIconDrawableId(int
			// layoutIconDrawableId); //设置自定义大图标Id

			// 注意：自定义样式的5个参数都必须设置，否则通知自定义样式会无法展示。

			// 为本地通知设置自定义通知样式
			localNotification.setNotificationBuilder(notificationBuilder);
			PushAgent mPushAgent = PushAgent.getInstance(mContext);
			mPushAgent.addLocalNotification(localNotification);

		}
}
